package com.ragdollcat.thirdaicodegenerate.ai.strategy;

import cn.hutool.core.util.StrUtil;
import com.ragdollcat.thirdaicodegenerate.enums.ChatHistoryMessageTypeEnum;
import com.ragdollcat.thirdaicodegenerate.model.entity.User;
import com.ragdollcat.thirdaicodegenerate.service.AppService;
import com.ragdollcat.thirdaicodegenerate.service.ChatHistoryService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;

@Component
@Slf4j
public class CommonFluxHandler {

    @Resource
    @Lazy
    private AppService appService;

    public Flux<String> handlerCommon(Flux<String> flux, ChatHistoryService chatHistoryService, Long appId, User user, Integer version) {
        StringBuilder stringBuilder = new StringBuilder();
        return flux
                // 累加响应内容
                .map(chunk -> {
                    stringBuilder.append(chunk);
                    return chunk;
                })
                // 完成时保存历史
                .doOnComplete(() -> {
                    String resp = stringBuilder.toString();
                    if (StrUtil.isNotEmpty(resp)) {
                        chatHistoryService.saveChatHistory(resp, appId, user.getId(), ChatHistoryMessageTypeEnum.AI.getValue(), version);
                        log.info("保存AI对话历史成功");
                    }
                })
                // 出错时保存错误信息
                .doOnError(ex -> {
                    String resp = "与AI对话错误：" + ex.getMessage();
                    chatHistoryService.saveChatHistory(resp, appId, user.getId(), ChatHistoryMessageTypeEnum.AI.getValue(), version);
                    log.info("保存AI错误对话历史成功");
                })
                .doOnCancel(() -> {
                    try {
                        appService.clearResource(appId, version);
                    } catch (Exception e) {
                        log.error("中断输出，清理资源错误，原因：", e);
                    }
                });
    }
}
